﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using fbasync.webcomponents;
using System.Collections.Generic;

namespace fbasync.web
{
    public partial class Notifications : FacebookPage
    {
        private Dictionary<string, string> _allocations = new Dictionary<string, string>();
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            send.Click += delegate
                {
                    Connection.SendNotificationCompleted +=
                        (sender, e2) =>
                        {
                            if (null != e2.Result)
                                result.Text = "sent to " + string.Join(", ", e2.Result.Select(r => r.ToString()).ToArray());
                        };

                    var targets = string.IsNullOrEmpty(to.Text) ? new List<long>() : to.Text.Split(',').Select(t => long.Parse(t)).ToList();
#pragma warning disable 618
                    Connection.SendNotificationAsync(targets, notification.Text, (NotificationTypes)Enum.Parse(typeof(NotificationTypes), bl.SelectedValue));
#pragma warning restore 618
                };

            Connection.AdminGetAllocationCompleted +=
                (sender, e2) =>
                {
                    lock (_allocations)
                        _allocations.Add(e2.UserState.ToString(), e2.Result.ToString());
                };

            Connection.AdminGetAllocationAsync(AllocationType.announcement_notifications_per_week, AllocationType.announcement_notifications_per_week);
            Connection.AdminGetAllocationAsync(AllocationType.email_disable_message_location, AllocationType.email_disable_message_location);
            Connection.AdminGetAllocationAsync(AllocationType.emails_per_day, AllocationType.emails_per_day);
            Connection.AdminGetAllocationAsync(AllocationType.notifications_per_day, AllocationType.notifications_per_day);
            Connection.AdminGetAllocationAsync(AllocationType.requests_per_day, AllocationType.requests_per_day);
        }

        protected override void OnPreRenderComplete(EventArgs e)
        {
            base.OnPreRenderComplete(e);

            //bind after all the async calls are done
            DataBind();
        }

        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);

            allocations.DataSource = _allocations;
        }
    }
}
